package com.example.androidlearning2200;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        Button btnPopMenu = findViewById(R.id.btnPopMenu);
        btnPopMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu = new PopupMenu(MenuActivity.this, btnPopMenu);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        clickMenuItem(menuItem);
                        return true;
                    }
                });
                popupMenu.getMenuInflater().inflate(R.menu.action_bar_menu, popupMenu.getMenu());
                popupMenu.show();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_bar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        clickMenuItem(item);
        return true;
    }

    /**
     * 显示Toast
     *
     * @param msg
     */
    private void showToast(String msg) {
        Toast.makeText(MenuActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 菜单项的点击响应
     *
     * @param menuItem
     */
    private void clickMenuItem(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.search:
                showToast("点击了搜索");
                break;
            case R.id.share:
                showToast("点击分享");
                break;
            case R.id.settings:
                showToast("点击了设置");
                break;
            case R.id.scan:
                showToast("点击了扫一扫");
                break;
        }
    }
}